package com.fivefu.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.fivefu.core.exception.FfSqlAnalysisException;
import com.fivefu.core.param.FFParam;
import com.fivefu.core.param.FFTableMapperParam;
import com.fivefu.core.pojo.FfSql;
import java.util.List;
import org.springframework.stereotype.Component;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/12
 */
@Component
public class GroupHandler implements  SqlHandler {

    @Override
    public void dealSql(JSONObject jsonObject, FfSql ffSql) throws FfSqlAnalysisException {
        List<String> list = ffSql.getUnProcessedTableNameList();
        StringBuffer groupBuffer = new StringBuffer();
        for (String s : list) {
            JSONObject tableObject =   jsonObject.getJSONObject(FFTableMapperParam.getExposeTableName(s));
            if (tableObject.containsKey(FFParam.KEY_GROUP)) {
                String groupStr = tableObject.getString(FFParam.KEY_GROUP);
                String groupArr[] = groupStr.split(",");
                for (String item : groupArr) {
                    if (groupBuffer.length() > 0) {
                        groupBuffer.append(", ");
                    }
                    groupBuffer.append(s).append(".").append(item);
                }
                tableObject.remove(FFParam.KEY_GROUP);
            }
        }
        if (groupBuffer.length() > 0) {
            ffSql.setGroup(" group by " + groupBuffer.toString());
        }
    }

    @Override
    public int order() {
        return 3;
    }

    private String errorMsg;

    @Override
    public String getErrMsg() {
        return this.errorMsg;
    }

    protected void setErrorMsg(String msg){
        this.errorMsg = msg;
    }

}
